import 'package:shared_preferences/shared_preferences.dart';
import '../models/period_model.dart';
// UserProfile导入已移除，因为文件不存在
import '../services/database_helper.dart';
import '../services/period_service.dart';
import '../services/pregnancy_service.dart';
import '../services/childcare_service.dart';

class UserManagementService {
  final DatabaseHelper _dbHelper = DatabaseHelper.instance;
  final PeriodService _periodService = PeriodService();
  final PregnancyService _pregnancyService = PregnancyService();
  final ChildcareService _childcareService = ChildcareService();
  late SharedPreferences _prefs;

  // 应用模式枚举
  static const modePeriod = 'period';
  static const modePregnancyPrep = 'pregnancy_prep';
  static const modePregnancy = 'pregnancy';
  static const modeChildcare = 'childcare';

  // 初始化服务
  Future<void> init() async {
    _prefs = await SharedPreferences.getInstance();
  }

  // 创建新用户
  Future createUser({
      required name,
    required email,
    required password,
    avatar,
    phoneNumber,
    dateOfBirth,
    height,
    weight,
    bloodType,
    currentMode = modePeriod,
  }) async {
    // 检查用户是否已存在
    final existingUsers = await _dbHelper.queryRows(DatabaseHelper.tableUser, where: {DatabaseHelper.columnUserEmail: email});
    if (existingUsers.isNotEmpty) {
      throw Exception('该邮箱已被注册');
    }

    // 哈希密码（简单实现，实际应用中应使用更安全的哈希算法）
    final hashedPassword = _hashPassword(password);

    // 创建用户配置文件
    final userMap = {
      'name': name,
      'email': email,
      'password_hash': hashedPassword,
      'avatar': avatar ?? '',
      'phone_number': phoneNumber ?? '',
      'date_of_birth': dateOfBirth?.toIso8601String() ?? '',
      'height': height ?? 0,
      'weight': weight ?? 0,
      'blood_type': bloodType ?? '',
      'current_mode': currentMode,
      'created_at': DateTime.now().toIso8601String(),
      'last_login': DateTime.now().toIso8601String(),
    };

    final userId = await _dbHelper.insert(DatabaseHelper.tableUser, userMap);

    // 初始化用户的应用设置
    await _initUserSettings(userId);

    // 切换到当前模式
    await switchMode(userId, currentMode!);

    // 返回用户信息（不包含密码）
    final userProfile = UserProfile.fromMap({
      ...userMap,
      'id': userId,
    });

    return userProfile;
  }

  // 用户登录
  Future login(email, password) async {
    final userDataList = await _dbHelper.queryRows(DatabaseHelper.tableUser, where: {DatabaseHelper.columnUserEmail: email});
    if (userDataList.isEmpty) {
      return null;
    }
    final existingUser = userDataList.first;

    // 验证密码
    final hashedPassword = _hashPassword(password);
    if (existingUser['password_hash'] != hashedPassword) {
      return null;
    }

    // 更新最后登录时间
    final userId = existingUser['id'];
    await _dbHelper.updateLastLogin(userId, DateTime.now());

    // 保存当前用户ID到共享偏好
    await _prefs.setInt('current_user_id', userId);

    // 返回用户信息（不包含密码）
    final userMap = Map<String, dynamic>.from(existingUser);
    userMap.remove('password_hash');
    return UserProfile.fromMap(userMap);
  }

  // 用户登出
  Future<void> logout() async {
    await _prefs.remove('current_user_id');
  }

  // 获取当前登录用户
  Future<UserProfile?> getCurrentUser() async {
    final userId = _prefs.getInt('current_user_id');
    if (userId == null) {
      return null;
    }

    final userDataList = await _dbHelper.queryRows(DatabaseHelper.tableUser, where: {DatabaseHelper.columnUserId: userId});
    final userData = userDataList.isNotEmpty ? userDataList.first : null;
    if (userData == null) {
      return null;
    }

    // 返回用户信息（不包含密码）
    final userMap = Map<String, dynamic>.from(userData);
    userMap.remove('password_hash');
    return UserProfile.fromMap(userMap);
  }

  // 获取所有用户列表
  Future getAllUsers() async {
    final usersData = await _dbHelper.queryRows(DatabaseHelper.tableUser);
    return usersData.map((userData) {
      final userMap = Map<String, dynamic>.from(userData);
      userMap.remove('password_hash');
      return UserProfile.fromMap(userMap);
    }).toList();
  }

  // 更新用户信息
  Future updateUser({
    required userId,
    name,
    email,
    password,
    avatar,
    phoneNumber,
    dateOfBirth,
    height,
    weight,
    bloodType,
  }) async {
    final userDataList = await _dbHelper.queryRows(DatabaseHelper.tableUser, where: {DatabaseHelper.columnUserId: userId});
    final userData = userDataList.isNotEmpty ? userDataList.first : null;
    if (userData == null) {
      throw Exception('用户不存在');
    }

    // 构建更新数据
    final updateData = {};

    if (name != null) updateData['name'] = name;
    if (email != null) updateData['email'] = email;
    if (password != null) updateData['password_hash'] = _hashPassword(password);
    if (avatar != null) updateData['avatar'] = avatar;
    if (phoneNumber != null) updateData['phone_number'] = phoneNumber;
    if (dateOfBirth != null) updateData['date_of_birth'] = dateOfBirth.toIso8601String();
    if (height != null) updateData['height'] = height;
    if (weight != null) updateData['weight'] = weight;
    if (bloodType != null) updateData['blood_type'] = bloodType;

    // 更新用户信息
    await _dbHelper.updateWhere(DatabaseHelper.tableUser, updateData as dynamic, {DatabaseHelper.columnUserId: userId} as dynamic);

    // 返回更新后的用户信息
    final updatedUserDataList = await _dbHelper.queryRows(DatabaseHelper.tableUser, where: {DatabaseHelper.columnUserId: userId});
    final updatedUserData = updatedUserDataList.isNotEmpty ? updatedUserDataList.first : null;
    if (updatedUserData == null) {
      throw Exception('更新用户信息失败');
    }

    final userMap = Map<String, dynamic>.from(updatedUserData);
    userMap.remove('password_hash');
    return UserProfile.fromMap(userMap);
  }

  // 删除用户
  Future deleteUser(userId) async {
    // 检查是否是当前登录用户
    final currentUserId = _prefs.getInt('current_user_id');
    if (currentUserId == userId) {
      // 如果是当前用户，先登出
      await logout();
    }

    // 删除用户相关的所有数据
    await _dbHelper.deleteUserAndAllData(userId);
  }

  // 切换用户模式
  Future switchMode(userId, mode) async {
    // 验证模式有效性
    if (![modePeriod, modePregnancyPrep, modePregnancy, modeChildcare].contains(mode)) {
      throw Exception('无效的应用模式');
    }

    // 更新用户当前模式
    await _dbHelper.updateUserMode(userId, mode);

    // 如果是当前登录用户，保存到共享偏好
    final currentUserId = _prefs.getInt('current_user_id');
    if (currentUserId == userId) {
      await _prefs.setString('current_mode', mode);
    }

    // 执行模式切换后的必要操作
    await _executeModeSwitchOperations(userId, mode);

    return true;
  }

  // 获取当前模式
  Future getCurrentMode(userId) async {
    // 优先从数据库获取
    final userDataList = await _dbHelper.queryRows(DatabaseHelper.tableUser, where: {DatabaseHelper.columnUserId: userId});
    final userData = userDataList.isNotEmpty ? userDataList.first : null;
    if (userData != null && userData.containsKey('current_mode')) {
      return userData['current_mode'];
    }

    // 如果是当前登录用户，从共享偏好获取
    final currentUserId = _prefs.getInt('current_user_id');
    if (currentUserId == userId) {
      return _prefs.getString('current_mode') ?? modePeriod;
    }

    // 默认返回经期模式
    return modePeriod;
  }

  // 获取用户数据概览（跨模式数据统计）
  Future getUserDataOverview(userId) async {
    final overview = {};

    // 经期模式数据统计
    final periods = await _periodService.getUserPeriods(userId);
    final symptoms = await _dbHelper.queryRows(DatabaseHelper.tableSymptom, where: {DatabaseHelper.columnUserId: userId});
    overview['periods_count'] = periods.length; // 移除不必要的空值检查
    overview['symptoms_count'] = symptoms.length;

    // 备孕模式数据统计
    final bbtRecords = await _dbHelper.queryRows(DatabaseHelper.tableBBTRecords, where: {DatabaseHelper.columnUserId: userId});
    final cmRecords = await _dbHelper.queryRows('cervical_mucus', where: {DatabaseHelper.columnUserId: userId});
    final ovulationTests = await _dbHelper.queryRows('ovulation_tests', where: {DatabaseHelper.columnUserId: userId});
    overview['bbt_records_count'] = bbtRecords.length;
    overview['cm_records_count'] = cmRecords.length;
    overview['ovulation_tests_count'] = ovulationTests.length;

    // 孕期模式数据统计
    final pregnancyInfo = await _pregnancyService.getPregnancyInfo(userId);
    final prenatalVisits = await _pregnancyService.getPrenatalVisits(userId);
    final fetalMovements = await _dbHelper.queryRows('fetal_movements', where: {DatabaseHelper.columnUserId: userId});
    overview['is_pregnant'] = (pregnancyInfo != null).toString();
    overview['prenatal_visits_count'] = prenatalVisits.length;
    overview['fetal_movements_count'] = fetalMovements.length;
    
    if (pregnancyInfo != null) {
      overview['current_week'] = pregnancyInfo.currentWeek;
      overview['due_date'] = pregnancyInfo.estimatedDueDate?.toIso8601String();
    }

    // 育儿模式数据统计
    final babies = await _childcareService.getUserBabies(userId);
    overview['babies_count'] = babies.length;
    
    // 统计每个宝宝的记录
    final babiesOverview = [];
    for (var baby in babies) {
      final growthRecords = await _childcareService.getGrowthRecords(baby.id!);
      final vaccineRecords = await _dbHelper.queryRows('baby_vaccines', where: {'baby_id': baby.id!});
      
      babiesOverview.add({
        'id': baby.id,
        'name': baby.name,
        'age_months': baby.ageInMonths,
        'growth_records_count': growthRecords.length,
        'vaccine_records_count': vaccineRecords.length,
      });
    }
    overview['babies_overview'] = babiesOverview;

    // 计算应用使用时长
    final userDataList = await _dbHelper.queryRows(DatabaseHelper.tableUser, where: {DatabaseHelper.columnUserId: userId});
    final userData = userDataList.isNotEmpty ? userDataList.first : null;
    if (userData != null && userData.containsKey('created_at')) {
      final createdAt = DateTime.parse(userData['created_at']);
      final daysUsing = DateTime.now().difference(createdAt).inDays;
      overview['days_using'] = daysUsing;
    }

    return overview;
  }

  // 数据迁移（从一个模式到另一个模式）
  Future migrateData(userId, fromMode, toMode) async {
    try {
      if (fromMode == modePeriod && toMode == modePregnancyPrep) {
        // 从经期模式迁移到备孕模式
        return await _migrateFromPeriodToPregnancyPrep(userId);
      } else if (fromMode == modePregnancyPrep && toMode == modePregnancy) {
        // 从备孕模式迁移到孕期模式
        return await _migrateFromPregnancyPrepToPregnancy(userId);
      } else if (fromMode == modePregnancy && toMode == modeChildcare) {
        // 从孕期模式迁移到育儿模式
        return await _migrateFromPregnancyToChildcare(userId);
      }
      return false;
    } catch (e) {
      // 数据迁移失败 - 已移除print语句
      return false;
    }
  }

  // 获取模式切换建议
  Future getModeSwitchSuggestions(userId) async {
    final suggestions = [];
    final currentMode = await getCurrentMode(userId);
    
    // 根据当前模式和用户数据提供建议
    switch (currentMode) {
      case modePeriod:
        // 检查是否有迹象表明用户可能在备孕
        final periods = await _periodService.getUserPeriods(userId);
        if (periods.length > 3) {
          // 有规律记录经期，可能有备孕需求
          suggestions.add({
            'title': '考虑备孕模式',
            'description': '您已经记录了多个月经周期，备孕模式可以帮助您更精确地追踪排卵和生育窗口。',
            'suggested_mode': modePregnancyPrep,
          });
        }
        break;
      
      case modePregnancyPrep:
        // 检查是否可能怀孕
        final periods = await _periodService.getUserPeriods(userId);
        final lastPeriod = periods.isNotEmpty ? periods.first : null;
        if (lastPeriod != null) {
          final daysSinceLastPeriod = DateTime.now().difference(DateTime.parse(lastPeriod['endDate'].toString())).inDays;
          if (daysSinceLastPeriod > 35) { // 超过预期周期较长时间
            suggestions.add({
              'title': '可能已怀孕',
              'description': '您的月经已经推迟一段时间，考虑切换到孕期模式开始记录孕期信息。',
              'suggested_mode': modePregnancy,
            });
          }
        }
        break;
      
      case modePregnancy:
        // 检查是否接近或已过预产期
        final pregnancyInfo = await _pregnancyService.getPregnancyInfo(userId);
        if (pregnancyInfo != null && pregnancyInfo.estimatedDueDate != null) {
            final daysUntilDue = pregnancyInfo.estimatedDueDate!.difference(DateTime.now()).inDays;
          if (daysUntilDue <= 14 || daysUntilDue < 0) { // 接近预产期或已过期
            suggestions.add({
              'title': '准备迎接宝宝',
              'description': '您即将或已经到了预产期，考虑切换到育儿模式开始记录宝宝信息。',
              'suggested_mode': modeChildcare,
            });
          }
        }
        break;
      
      case modeChildcare:
        // 对于育儿模式的用户，可能不需要切换到其他模式
        // 但可以建议继续记录其他健康数据
        break;
    }
    
    return suggestions;
  }

  // 合并用户数据（当有多个用户需要合并时）
  Future mergeUserData(sourceUserIdValue, targetUserIdValue) async {
    try {
        // 检查目标用户是否存在
        final targetUserList = await _dbHelper.queryRows(DatabaseHelper.tableUser, where: {DatabaseHelper.columnUserId: targetUserIdValue});
        final targetUser = targetUserList.isNotEmpty ? targetUserList.first : null;
      if (targetUser == null) {
        throw Exception('目标用户不存在');
      }

      // 开始事务
      await _dbHelper.transaction((txn) async {
        // 合并经期数据
        await _mergePeriodData(sourceUserIdValue, targetUserIdValue);
        
        // 合并备孕数据
        await _mergePregnancyPrepData(sourceUserIdValue, targetUserIdValue);
        
        // 合并孕期数据（如果目标用户没有孕期数据）
        final targetPregnancyInfo = await _pregnancyService.getPregnancyInfo(targetUserIdValue);
        if (targetPregnancyInfo == null) {
          await _mergePregnancyData(sourceUserIdValue, targetUserIdValue);
        }
        
        // 合并育儿数据
        await _mergeChildcareData(sourceUserIdValue, targetUserIdValue);
      });

      return true;
    } catch (e) {
      // 合并用户数据失败 - 已移除print语句
      return false;
    }
  }

  // 私有辅助方法

  // 密码哈希（简单实现，实际应用中应使用更安全的哈希算法）
  _hashPassword(password) {
    // 这里只是一个简单的演示，实际应用中应使用如bcrypt、Argon2等安全的哈希算法
    return password.hashCode.toString();
  }

  // 初始化用户设置
  Future _initUserSettings(userId) async {
    final defaultSettings = {
      'notification_enabled': 'true',
      'dark_mode': 'false',
      'language': 'zh_CN',
      'reminder_time': '09:00',
      'period_reminder_days': '1',
      'backup_enabled': 'true',
      'data_usage_tracking': 'true',
    };

    await _dbHelper.insertUserSettings(userId, defaultSettings);
  }

  // 执行模式切换后的操作
  Future _executeModeSwitchOperations(userId, mode) async {
    switch (mode) {
      case modePeriod:
        // 经期模式特定初始化
        final periodSettings = await _dbHelper.getUserSettings(userId);
        if (periodSettings == null || periodSettings.isEmpty) {
          await _dbHelper.insertUserSettings(userId, {
            'period_length': '5',
            'cycle_length': '28',
            'period_reminder_days': '1',
          });
        }
        break;
      
      case modePregnancyPrep:
        // 备孕模式特定初始化
        final prepSettings = await _dbHelper.getUserSettings(userId);
        if (prepSettings == null || prepSettings.isEmpty) {
          await _dbHelper.insertUserSettings(userId, {
            'temp_measurement_time': '06:00',
            'fertility_reminder_enabled': 'true',
            'tracking_preference': 'all', // all, temp_only, cm_only
          });
        }
        break;
      
      case modePregnancy:
        // 孕期模式特定初始化
        // 检查是否需要初始化孕期信息
        final pregnancyInfo = await _pregnancyService.getPregnancyInfo(userId);
        if (pregnancyInfo == null) {
          // 如果没有孕期信息，提示用户输入
          // 这里只是记录一个标志，表示需要引导用户输入
          // 查询用户设置的ID
          final userSettings = await _dbHelper.queryRows('user_settings', where: {DatabaseHelper.columnUserId: userId});
          if (userSettings.isNotEmpty) {
            final settingsId = int.parse(userSettings.first['id'].toString());
            await _dbHelper.update('user_settings', {'needs_pregnancy_info': 'true'}, settingsId);
          }
        }
        break;
      
      case modeChildcare:
        // 育儿模式特定初始化
        final childcareSettings = await _dbHelper.getUserSettings(userId);
        if (childcareSettings == null || childcareSettings.isEmpty) {
          await _dbHelper.insertUserSettings(userId, {
            'growth_chart_type': 'WHO',
            'vaccine_reminders_enabled': 'true',
            'development_tracking_enabled': 'true',
          });
        }
        break;
    }
  }

  // 从经期模式迁移到备孕模式
  Future _migrateFromPeriodToPregnancyPrep(userId) async {
    try {
      // 获取经期历史数据
      final periods = await _periodService.getUserPeriods(userId);
      if (periods.isEmpty) {
        return false;
      }

      // 计算平均周期长度和经期长度
      final cycleLengths = [];
      final periodLengths = [];

      for (var i = 0; i < periods.length - 1; i++) {
        final cycleLength = DateTime.parse(periods[i]['startDate'].toString()).difference(DateTime.parse(periods[i + 1]['startDate'].toString())).inDays;
        if (cycleLength > 0 && cycleLength < 60) { // 合理的周期长度范围
          cycleLengths.add(cycleLength);
        }
        
        final periodLength = DateTime.parse(periods[i]['endDate'].toString()).difference(DateTime.parse(periods[i]['startDate'].toString())).inDays + 1;
        if (periodLength > 0 && periodLength < 10) { // 合理的经期长度范围
          periodLengths.add(periodLength);
        }
      }

      // 如果有足够的数据，计算平均值并更新到备孕设置
      if (cycleLengths.isNotEmpty && periodLengths.isNotEmpty) {
        // 使用安全的方式计算平均值
        dynamic totalCycleLength = 0;
        for (var length in cycleLengths) {
          totalCycleLength = totalCycleLength + length;
        }
        dynamic totalPeriodLength = 0;
        for (var length in periodLengths) {
          totalPeriodLength = totalPeriodLength + length;
        }
        dynamic avgCycleLength = totalCycleLength / cycleLengths.length;
        dynamic avgPeriodLength = totalPeriodLength / periodLengths.length;
          // 基于平均周期长度设置初始的排卵预测
          final estimatedOvulationDay = avgCycleLength - 14; // 通常排卵发生在下次月经前14天
          
          // 查询用户设置的ID
          final userSettings = await _dbHelper.queryRows('user_settings', where: {DatabaseHelper.columnUserId: userId});
          if (userSettings.isNotEmpty) {
            final settingsId = int.parse(userSettings.first['id'].toString());
            await _dbHelper.update('user_settings', {
              'avg_cycle_length': avgCycleLength.toString(),
              'avg_period_length': avgPeriodLength.toString(),
              'fertile_window_days': '6', // 典型的生育窗口长度
              'estimated_ovulation_day': estimatedOvulationDay.toString(),
            }, settingsId);
          }
      }

      // 切换模式
      await switchMode(userId, modePregnancyPrep);
      
      return true;
    } catch (e) {
      // 从经期模式迁移到备孕模式失败 - 已移除print语句
      return false;
    }
  }

  // 从备孕模式迁移到孕期模式
  Future _migrateFromPregnancyPrepToPregnancy(userId) async {
    try {
      // 获取最后一次经期信息
      final periods = await _periodService.getUserPeriods(userId);
      final lastPeriod = periods.isNotEmpty ? periods.first : null;
      if (lastPeriod == null) {
        return false;
      }

      // 计算预产期（基于末次月经日期）- 已移除未使用的变量声明

      // 初始化孕期信息
      await _pregnancyService.initializePregnancy(
        userId: userId,
        lastPeriodDate: DateTime.parse(lastPeriod['startDate'].toString()),
        notes: '从备孕模式迁移创建',
      );

      // 保存迁移信息
      final userSettings = await _dbHelper.queryRows('user_settings', where: {DatabaseHelper.columnUserId: userId});
      if (userSettings.isNotEmpty) {
        final settingsId = userSettings.first['id'];
        await _dbHelper.update('user_settings', {
          'pregnancy_start_source': 'pregnancy_prep_mode',
          'migration_date': DateTime.now().toIso8601String(),
        }, settingsId);
      }

      // 切换模式
      await switchMode(userId, modePregnancy);
      
      return true;
    } catch (e) {
      // 从备孕模式迁移到孕期模式失败 - 已移除print语句
      return false;
    }
  }

  // 从孕期模式迁移到育儿模式
  Future _migrateFromPregnancyToChildcare(userId) async {
    try {
      // 获取孕期信息
      final pregnancyInfo = await _pregnancyService.getPregnancyInfo(userId);
      if (pregnancyInfo == null) {
        return false;
      }

      // 计算宝宝的出生日期（使用当前日期作为默认值）
      final dateOfBirth = DateTime.now();

      // 添加宝宝信息
      await _childcareService.addBabyInfo(
        userId: userId,
        name: '我的宝宝', // 用户可以稍后修改
        dateOfBirth: dateOfBirth,
        gender: 'unknown', // 用户可以稍后修改
        birthWeight: 3.5, // 默认值，用户可以稍后修改
        birthHeight: 50.0, // 默认值，用户可以稍后修改
        deliveryMethod: '未知',
        notes: '从孕期模式迁移创建',
      );

      // 保存迁移信息
      final userSettings = await _dbHelper.queryRows('user_settings', where: {DatabaseHelper.columnUserId: userId});
      if (userSettings.isNotEmpty) {
        final settingsId = userSettings.first['id'];
        await _dbHelper.update('user_settings', {
          'childcare_start_source': 'pregnancy_mode',
          'migration_date': DateTime.now().toIso8601String(),
        }, settingsId);
      }

      // 切换模式
      await switchMode(userId, modeChildcare);
      
      return true;
    } catch (e) {
      // 从孕期模式迁移到育儿模式失败 - 已移除print语句
      return false;
    }
  }

  // 合并经期数据
  Future _mergePeriodData(sourceUserIdValue, targetUserIdValue) async {
    final periods = await _dbHelper.getUserPeriods(sourceUserIdValue);
    for (var period in periods) {
      final newPeriod = Map<String, dynamic>.from(period);
      newPeriod['user_id'] = targetUserIdValue;
      // 移除可能存在的ID，让数据库自动分配新ID
      newPeriod.remove('id');
      await _dbHelper.insert('period_records', newPeriod);
    }

    final symptoms = await _dbHelper.getUserSymptoms(sourceUserIdValue);
    for (var symptom in symptoms) {
      final newSymptom = Map<String, dynamic>.from(symptom);
      newSymptom['user_id'] = targetUserIdValue;
      newSymptom.remove('id');
      await _dbHelper.insert('symptoms', newSymptom);
    }
  }

  // 合并备孕数据
  Future _mergePregnancyPrepData(sourceUserIdValue, targetUserIdValue) async {
    // 合并基础体温数据
    final bbtRecords = await _dbHelper.queryRows('basal_body_temp', where: {DatabaseHelper.columnUserId: sourceUserIdValue});
    for (var record in bbtRecords) {
      final newRecord = Map<String, dynamic>.from(record);
      newRecord['user_id'] = targetUserIdValue;
      newRecord.remove('id');
      await _dbHelper.insert('basal_body_temp', newRecord);
    }

    // 合并宫颈粘液数据
    final cmRecords = await _dbHelper.queryRows('cervical_mucus', where: {DatabaseHelper.columnUserId: sourceUserIdValue});
    for (var record in cmRecords) {
      final newRecord = Map<String, dynamic>.from(record);
      newRecord['user_id'] = targetUserIdValue;
      newRecord.remove('id');
      await _dbHelper.insert('cervical_mucus', newRecord);
    }

    // 合并排卵测试数据
    final ovulationTests = await _dbHelper.queryRows('ovulation_tests', where: {DatabaseHelper.columnUserId: sourceUserIdValue});
    for (var test in ovulationTests) {
      final newTest = Map<String, dynamic>.from(test);
      newTest['user_id'] = targetUserIdValue;
      newTest.remove('id');
      await _dbHelper.insert('ovulation_tests', newTest);
    }
  }

  // 合并孕期数据
  Future _mergePregnancyData(sourceUserIdValue, targetUserIdValue) async {
    // 检查源用户是否有孕期信息
    final pregnancyInfo = await _dbHelper.getPregnancyInfo(sourceUserIdValue);
    if (pregnancyInfo != null) {
      final newPregnancyInfo = Map<String, dynamic>.from(pregnancyInfo);
      newPregnancyInfo['user_id'] = targetUserIdValue;
      newPregnancyInfo.remove('id');
      await _dbHelper.insert('pregnancy_info', newPregnancyInfo);

      // 合并产检记录
      final prenatalVisits = await _dbHelper.queryRows('prenatal_visits', where: {DatabaseHelper.columnUserId: sourceUserIdValue});
      for (var visit in prenatalVisits) {
        final newVisit = Map<String, dynamic>.from(visit);
        newVisit['user_id'] = targetUserIdValue;
        newVisit.remove('id');
        await _dbHelper.insert('prenatal_visits', newVisit);
      }

      // 合并胎动记录
      final fetalMovements = await _dbHelper.queryRows('fetal_movements', where: {DatabaseHelper.columnUserId: sourceUserIdValue});
      for (var movement in fetalMovements) {
        final newMovement = Map<String, dynamic>.from(movement);
        newMovement['user_id'] = targetUserIdValue;
        newMovement.remove('id');
        await _dbHelper.insert('fetal_movements', newMovement);
      }
    }
  }

  // 合并育儿数据
  Future _mergeChildcareData(sourceUserIdValue, targetUserIdValue) async {
    final babies = await _dbHelper.getUserBabies(sourceUserIdValue);
    for (var baby in babies) {
      // 创建新宝宝
      final newBaby = Map<String, dynamic>.from(baby);
      newBaby['user_id'] = targetUserIdValue;
      newBaby.remove('id');
      final newBabyId = await _dbHelper.insert(DatabaseHelper.tableBabyInfo, newBaby);

      // 合并宝宝相关数据
      // 成长记录
      final growthRecords = await _dbHelper.getBabyGrowthRecords(int.parse(baby['id'].toString()));
      for (var record in growthRecords) {
        final newRecord = Map<String, dynamic>.from(record);
        newRecord['baby_id'] = newBabyId;
        newRecord.remove('id');
        await _dbHelper.insert('growth_records', newRecord);
      }

      // 疫苗记录
      final vaccineRecords = await _dbHelper.queryRows('baby_vaccines', where: {'baby_id': int.parse(baby['id'].toString())});
      for (var record in vaccineRecords) {
        final newRecord = Map<String, dynamic>.from(record);
        newRecord['baby_id'] = newBabyId;
        newRecord.remove('id');
        await _dbHelper.insert('baby_vaccines', newRecord);
      }

      // 其他育儿相关数据...
    }
  }
}